package cn.hyy.hrm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64Encoder;
import cn.hyy.basic.util.AjaxResult;
import cn.hyy.basic.util.StrUtils;
import cn.hyy.hrm.RedisClient;
import cn.hyy.hrm.client.SMSClient;
import cn.hyy.hrm.util.CodeConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/code")
public class CodeController {

    private Logger logger = LoggerFactory.getLogger(CodeController.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private SMSClient smsClient;

    /**
     * 生成图片验证码
     * @return
     */
    @GetMapping("/imageCode")
    public AjaxResult generateImageCode(@RequestParam("uuid")String uuid){

        try {
            logger.debug("uuid值为:"+uuid);

            //1、使用工具生成验证码
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
            //2、获取出来验证码缓存到redis中
            String code = captcha.getCode();
            logger.debug("********************生成的验证码:"+code+"****************");
            String key = "IMAGECODE:"+ uuid;
            redisClient.setStrEX(key,code,5*60);

            //3、使用base64对图片内容进行编码
            byte[] imageBytes = captcha.getImageBytes();
            String imgStr = Base64Encoder.encode(imageBytes);

            return AjaxResult.me().setSuccess(true).setMessage("成功!").setResultObj(imgStr);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败!");
        }
    }

    /**
     * 发送短信验证码
     * @param uuid 前端的标识
     * @param imageCode 图片验证码
     * @param phoneNum 手机号码
     * @return
     */
    @GetMapping("/smsCode")
    public AjaxResult sendSMSCode(@RequestParam("uuid")String uuid,
                                  @RequestParam("imageCode")String imageCode,
                                  @RequestParam("phoneNum")String phoneNum){


        logger.debug("********************uuid:"+uuid+"****************");
        logger.debug("********************imageCode:"+imageCode+"****************");
        logger.debug("********************phoneNum:"+phoneNum+"****************");
        //参数验证
        if(StringUtils.isEmpty(uuid)){
            return AjaxResult.me().setSuccess(false).setMessage("发送失败！");
        }
        if(StringUtils.isEmpty(imageCode)){
            return AjaxResult.me().setSuccess(false).setMessage("请输入图形验证码！");
        }
        if(StringUtils.isEmpty(phoneNum)){
            return AjaxResult.me().setSuccess(false).setMessage("请输入手机号码！");
        }


        //图形验证码的比较
        String redisCode = (String) redisClient.getStr(CodeConst.IMAGE_CODE_PRE + uuid).getResultObj();
        if(!imageCode.equals(redisCode)){
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确的图形验证");
        }

        String sendCode = null;

        //判断redis中的短信验证码是否存在
        String RedisSmsCode = (String) redisClient.getStr(CodeConst.SMS_CODE_PRE+phoneNum).getResultObj();
        if(StringUtils.isEmpty(RedisSmsCode)){
            //不存在 没有发送过或者已经过期
            String SMSCode = StrUtils.getRandomString(6);
            //保存redis  SMSCODE:{phone} = code,时间(判断重发)  还要设置验证码的过期时间
            redisClient.setStrEX(CodeConst.SMS_CODE_PRE+phoneNum,SMSCode+","+System.currentTimeMillis(),10*60);
            sendCode = SMSCode;
        }else{
            //存在 验证码发送过还没有过期
            String[] strings = RedisSmsCode.split(",");
            String code = strings[0];
            Long lastTime = Long.valueOf(strings[1]);//上次发送的时间

            Long currentTime = System.currentTimeMillis();//当前时间
            //判断是否需要重发
            if(currentTime-lastTime<=30*1000){
                return AjaxResult.me().setSuccess(false).setMessage("非法请求");
            }
            redisClient.setStrEX(CodeConst.SMS_CODE_PRE+phoneNum,code+","+currentTime,10*60);

            sendCode = code;

        }

        //发送短信验证码
        smsClient.sendRegSMSCode(phoneNum,sendCode);

        return AjaxResult.me().setSuccess(true).setMessage("发送成功!");
    }


}
